package controllers

import (
	"findme-api/models"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
)

type QueryLabelController struct {
	beego.Controller
}

//func (c *QueryLabelController) LabelAllowCross() {
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS")    //允许post访问
//	//c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
//	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
//}

type Label struct {
	Id string `json:"id"`
	Labelid string `json:"labelid"`
	Labeltype string `json:"labeltype"`
	Labeluser   string   `json:"labeluser"`
	Gender string `json:"gender"`
	Position   string   `json:"position"`
	Registered  string    `json:"Registered"`
	Unit string `json:"unit"`
	Department string `json:"department"`
	Phonenumber string `json:"phonenumber"`
	Idcard string `json:"idcard"`
	Area   string   `json:"coordinate"`
	Electricquantity string `json:"electricquantity"`
}


type CapLabel struct {
	Id string `json:"id"`
	Labelid string `json:"labelid"`
	Labeltype string `json:"labeltype"`
	Labeluser   string   `json:"labeluser"`
	Gender string `json:"gender"`
	Department string `json:"department"`
	Phonenumber string `json:"phonenumber"`
	Idcard string `json:"idcard"`
	Coordinate string `json:"coordinate"`
	Networkstatus string `json:"networkstatus"`
	Opencamera string `json:"opencamera"`
	Nearelectricity string `json:"nearelectricity"`
	Badhandstatus string `json:"badhandstatus"`
	Wearingstatus string `json:"wearingstatus"`
}



type Labelonline struct {
	Id string `json:"id"`
	Labelid string `json:"labelid"`
	Labeltype string `json:"labeltype"`
	Labeluser   string   `json:"labeluser"`
	Gender string `json:"gender"`
	Position   string   `json:"position"`
	Registered  string    `json:"Registered"`
	Unit string `json:"unit"`
	Department   string   `json:"department"`
	Phonenumber string `json:"phonenumber"`
	Idcard string `json:"idcard"`
	Area   string   `json:"coordinate"`
	Networkstatus string `json:"networkstatus"`
	Electricquantity string `json:"electricquantity"`
	Opencamera string `json:"opencamera"`
	Nearelectricity string `json:"nearelectricity"`
	Badhandstatus string `json:"badhandstatus"`
	Wearingstatus string `json:"wearingstatus"`
	Online string `json:"online"`
}

type Department struct {
	Department string `json:"department"`
}

type Area struct {
	Area string `json:"area"`
}

type Biglabel struct {
	Label
}

type Bigcaplabel struct {
	CapLabel
}

type LJSONS1 struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	Alldepartment []Department `json:"alldepartment"`
	Allarea []Area `json:"allarea"`
	DATA []Label  `json:"data"`
}

type LJSONS2 struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	DATA []CapLabel  `json:"data"`
}


type LJSONS3 struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	Alldepartment []Department `json:"alldepartment"`
	Allarea []Area `json:"allarea"`
	DATA []Labelonline  `json:"data"`
}



//查询所有的标签，安全帽和GPS都使用这个接口
func (this *QueryLabelController) QueryAllLabel(){
	FileLogs.Info("===查询所有的标签，安全帽和GPS都使用这个接口===")
	//this.LabelAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	page := this.GetString("page")
	size := this.GetString("size")
	searchlittletype := this.GetString("searchlittletype")
	labelDataChan := make(chan string, 100000)
	totalItem := models.ReadLabel(labelDataChan,company,page,size,searchlittletype)
	labeldata1 := []Label{}
	tempdata1 := Label{"","","","","","","","","","","","",""}
	labeldata2 := []CapLabel{}
	tempdata2 := CapLabel{"","","","","","","","","","","","","",""}
	labeldata3 := []Labelonline{}
	tempdata3 := Labelonline{"","","","","","","","","","","","","","","","","","",""}
	departments := models.Getalldepartment(company)
	areas := models.Getallareas(company)

	departmentt := []Department{}
	departsegs := strings.Split(departments, "，")
	for _,item := range departsegs{
		//fmt.Println(item)
		departmentt = append(departmentt,Department{item})
	}

	areaa := []Area{}
	areasegs := strings.Split(areas, "，")
	for _,item := range areasegs{
		areaa = append(areaa,Area{item})
	}


	//遍历信道，读取数据
	var i int = 0
	var lenalarmchan = len(labelDataChan)
	if lenalarmchan != 0 {
		for item := range labelDataChan {
			if searchlittletype == "1" {
				itemsegments := strings.Split(item, "and")
				tempdata1 = Label{itemsegments[0], itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5], itemsegments[6], itemsegments[7], itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12]}
				labeldata1 = append(labeldata1, tempdata1)
				if i == (lenalarmchan - 1) {
					break
				}
				i++
			}else if searchlittletype == "2"{
				itemsegments := strings.Split(item, "and")
				tempdata2 = CapLabel{itemsegments[0], itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5], itemsegments[6], itemsegments[7], itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12],itemsegments[13]}
				labeldata2 = append(labeldata2, tempdata2)
				if i == (lenalarmchan - 1) {
					break
				}
				i++
			}else if searchlittletype == "3"{
				itemsegments := strings.Split(item, "and")
				tempdata3 = Labelonline{   itemsegments[0],
					                  itemsegments[1],
					                  itemsegments[2],
					                  itemsegments[3],
					                  itemsegments[4],
					                  itemsegments[5],
					                    itemsegments[6],
					                    itemsegments[7],
					                    itemsegments[8],
					                    itemsegments[10],
					                    itemsegments[9],
					                    itemsegments[11],
					                    itemsegments[12],
					                    itemsegments[13],
					                    itemsegments[14],
					                    itemsegments[15],
					                    itemsegments[16],
					                    itemsegments[17],
					                    itemsegments[18]}
				labeldata3 = append(labeldata3, tempdata3)
				if i == (lenalarmchan - 1) {
					break
				}
				i++
			}
		}
		if searchlittletype == "1" {
			data := &LJSONS1{0, totalItem, departmentt,areaa,labeldata1}
			this.Data["json"] = data
			this.ServeJSON()
		}else if searchlittletype == "2" {
			data := &LJSONS2{0, totalItem, labeldata2}
			this.Data["json"] = data
			this.ServeJSON()
		}else if searchlittletype == "3"{
			data := &LJSONS3{0, totalItem, departmentt,areaa,labeldata3}
			this.Data["json"] = data
			this.ServeJSON()
		}

	}else {
		if searchlittletype == "1" {
			labeldata1 = append(labeldata1, tempdata1)
			data := &LJSONS1{1, totalItem, []Department{},[]Area{},labeldata1}
			this.Data["json"] = data
			this.ServeJSON()
		} else if searchlittletype == "2" {
			labeldata2 = append(labeldata2, tempdata2)
			data := &LJSONS2{1, totalItem, labeldata2}
			this.Data["json"] = data
			this.ServeJSON()
		}else if searchlittletype == "3"{
			labeldata3 = append(labeldata3, tempdata3)
			data := &LJSONS3{1, totalItem, []Department{},[]Area{},labeldata3}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
}


//搜索标签，安全帽和GPS都使用这个接口
func (this *QueryLabelController) SearchLabel() {
	FileLogs.SetLogger("===查询所有标签===")
	//this.LabelAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	tokeninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(tokeninfo)
	page := this.GetString("page")
	size := this.GetString("size")
	message := this.GetString("searchterm")
	searchlittletype := this.GetString("searchlittletype")
	pageint,_ := strconv.Atoi(page)
	sizeint, _ := strconv.Atoi(size)
	slice := []uint64{}
	//加载标签索引，slice为搜到的数据索引序号
	Search(message,&slice,username,"label",searchlittletype)
	//fmt.Println(slice)

	//fmt.Println(subject)
	//var allslice = []string{}
	labelDataChan := make(chan string, 100000)
	totalItem :=  models.SearchLabel(labelDataChan,username,searchlittletype)
	fmt.Println(totalItem)
	labeldata1 := []Label{}
	tempdata1 := Label{"","","","","","","","","","","","",""}
	labeldata2 := []CapLabel{}
	tempdata2 := CapLabel{"","","","","","","","","","","","","",""}
	labeldata3 := []Labelonline{}
	tempdata3 := Labelonline{"","","","","","","","","","","","","","","","","","",""}

	//遍历信道，读取数据
	var i int = 1//索引计数
	var j int = 1 //用于返回分页
	var lenalarmchan = len(labelDataChan)
	if len(slice) != 0 {
		for item := range labelDataChan {
			for _, v := range slice {

				if i == int(v) {
					//分页
					if j > (pageint-1)*sizeint && j <= pageint*sizeint {
						itemsegments := strings.Split(item, "and")
						//fmt.Println(itemsegments)
						if searchlittletype == "1" {
							tempdata1 = Label{strconv.Itoa(j), itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5], itemsegments[6], itemsegments[7], itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12]}
							labeldata1 = append(labeldata1, tempdata1)
						} else if searchlittletype == "2" {
							tempdata2 = CapLabel{strconv.Itoa(j), itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5], itemsegments[6], itemsegments[7], itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12],itemsegments[13]}
							labeldata2 = append(labeldata2, tempdata2)
						} else if searchlittletype == "3"{
							tempdata3 = Labelonline{strconv.Itoa(j), itemsegments[1], itemsegments[2], itemsegments[3], itemsegments[4], itemsegments[5], itemsegments[6], itemsegments[7], itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12],itemsegments[13],itemsegments[14],itemsegments[15],itemsegments[16],itemsegments[17],itemsegments[18]}
							labeldata3 = append(labeldata3, tempdata3)
						}
					}
					j++
				}
			}
			if i == lenalarmchan {
				break
			}
			i++
		}
		if searchlittletype == "1" {
			data := &LJSONS1{0, len(slice), []Department{},[]Area{},labeldata1}
			this.Data["json"] = data
			this.ServeJSON()
		} else if searchlittletype == "2" {
			data := &LJSONS2{0, len(slice), labeldata2}
			this.Data["json"] = data
			this.ServeJSON()
		} else if searchlittletype == "3" {
			data := &LJSONS3{0, len(slice), []Department{},[]Area{},labeldata3}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}else {
		if searchlittletype == "1" {
			labeldata1 = append(labeldata1, tempdata1)
			//fmt.Println(labeldata1)
			data := &LJSONS1{1, len(slice), []Department{},[]Area{},labeldata1}
			this.Data["json"] = data
			this.ServeJSON()
		} else if searchlittletype == "2" {
			labeldata2 = append(labeldata2, tempdata2)
			//fmt.Println(labeldata2)
			data := &LJSONS2{1, len(slice), labeldata2}
			this.Data["json"] = data
			this.ServeJSON()
		} else if searchlittletype == "3" {
			labeldata3 = append(labeldata3, tempdata3)
			//fmt.Println(labeldata2)
			data := &LJSONS3{1, len(slice), []Department{},[]Area{},labeldata3}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
}



//根据标签id修改标签信息
func (this *QueryLabelController) ChangeLabelById() {
	FileLogs.Info("===根据标签id修改标签信息===")
	//this.LabelAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	FileLogs.Info(company)
	//var obs []CapLabel
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	//fmt.Println(string(body))
	labelarray := Getinfofromjson(string(body))
	//fmt.Println(labelarray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	for i := 0; i < len(labelarray); i++ {
		_, err := o.Raw("update label_info set labeluser = ?, gender = ?,position=?, registered = ?, department= ?,phonenumber=? ,idcard=?, coordinate = ? where labelid = ?",
			labelarray[3], labelarray[4], labelarray[5], labelarray[6], labelarray[8],labelarray[9],labelarray[10],labelarray[11], labelarray[1]).Exec()
		if err != nil {
			FileLogs.Info("更新失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}




//修改网络状态
func (this *QueryLabelController)ChangeCapById(){
	FileLogs.Info("===修改网络状态===")
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	labelid := this.GetString("labelid")
	networkstatus := this.GetString("networkstatus")
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}

	o := orm.NewOrm()
	_, err := o.Raw("update label_info set networkstatus = ? where labelid = ? and unit = ?",networkstatus,labelid,company).Exec()
	if err != nil{
		data := &JSONS{1}
		this.Data["json"] = data
		this.ServeJSON()
			}
	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}


//修改某个标签的摄像头开启位
func (this *QueryLabelController)ChangeCameraById(){
	labelid := this.GetString("labelid")
	o := orm.NewOrm()
	_, err := o.Raw("update label_info set opencamera = ? where labelid = ?","0",labelid).Exec()
	if err != nil{
		fmt.Println("更新失败！")
		this.Ctx.WriteString("changelabelfailed")
	}
	this.Ctx.WriteString("changcameradone")
}


//根据标签id删除标签
func (this *QueryLabelController) DeleteLabelById() {
	FileLogs.Info("===根据标签id删除标签===")
	//this.LabelAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	FileLogs.Info(company)
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	//fmt.Println(string(body))
	labelidarray := Getinfofromarray(string(body))
	//fmt.Println(labelidarray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	for i := 0; i < len(labelidarray); i++{
		_, err := o.Raw("delete from  label_info  where labelid = ? and unit = ?",labelidarray[i],company).Exec()
		if err != nil{
			FileLogs.Info("删除失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}

	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}


//群发告警，根据标签id修改告警标志位
func (this *QueryLabelController) AlarmgroupById() {
	FileLogs.Info("===群发告警，根据标签id修改告警标志位===")
	//this.LabelAllowCross()
	//fmt.Println("收到群发告警")
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	FileLogs.Info(company)
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	//fmt.Println(string(body))
	labelidarray := Getinfofromarray(string(body))
	//fmt.Println(labelidarray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	for i := 0; i < len(labelidarray); i++{
		_, err := o.Raw("update label_info set alarmflag = ? where labelid = ? and unit = ?", "1",labelidarray[i],company).Exec()
		if err != nil{
			FileLogs.Info("更新失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}

	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}


//根据部门区域查询标签
func (this *QueryLabelController)SearchByCondition() {
	FileLogs.Info("===根据部门区域查询标签===")
	//this.LabelAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	department := this.GetString("department")
	coordinate := this.GetString("coordinate")
	page := this.GetString("page")
	size := this.GetString("size")
	labelDataChan := make(chan string, 100000)
	totalItem := models.Readbycondition(labelDataChan,company,department,coordinate,page,size)
	var i int = 0
	labeldata3 := []Labelonline{}
	tempdata3 := Labelonline{"","","","","","","","","","","","","","","","","","",""}

	var lenlabelchan = len(labelDataChan)
	if  lenlabelchan != 0 {
		for item := range labelDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			//fmt.Println(itemsegments[6])
			tempdata := Labelonline{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5],itemsegments[6],itemsegments[7],itemsegments[8],itemsegments[9],itemsegments[10],itemsegments[11],itemsegments[12],itemsegments[13],itemsegments[14],itemsegments[15],itemsegments[16],itemsegments[17],itemsegments[18]}
			labeldata3 = append(labeldata3,tempdata )
			if i == (lenlabelchan - 1) {
				break
			}
			i++
		}
		data := &LJSONS3{0,totalItem,[]Department{},[]Area{},labeldata3}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		labeldata3 = append(labeldata3,tempdata3)
		data := &LJSONS3{1, 0, []Department{},[]Area{},labeldata3}
		this.Data["json"] = data
		this.ServeJSON()
	}
}